package com.xinqi.modules.databank.v2.service.student.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinqi.common.base.response.R;
import com.xinqi.common.core.enums.CourseResourseStudyStatusEnum;
import com.xinqi.modules.course.clazz.client.ClassStudentClient;
import com.xinqi.modules.course.clazz.dto.req.ClassStudentQueryDTO;
import com.xinqi.modules.course.clazz.dto.rsp.ClassStudentResultDTO;
import com.xinqi.modules.databank.v2.domain.CourseResourceEntity;
import com.xinqi.modules.databank.v2.domain.CourseResourceInteractionLogEntity;
import com.xinqi.modules.databank.v2.domain.CourseResourceStudentLogEntity;
import com.xinqi.modules.databank.v2.manager.CourseResourceStudentLogManager;
import com.xinqi.modules.databank.v2.manager.ResourceInteractionLogManager;
import com.xinqi.modules.databank.v2.service.student.ResourceStudentLogService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 资料库学生日志记录 业务层
 * @author dzy
 */
@Service
@RequiredArgsConstructor
public class ResourceStudentLogServiceImpl implements ResourceStudentLogService {

    private final CourseResourceStudentLogManager resourceStudentLogManager;

    private final ResourceInteractionLogManager resourceInteractionLogManager;

    private final ClassStudentClient classStudentClient;

    /**
     * 添加单个学生日记记录信息
     * @author dzy
     */
    @Override
    public void syncStudentLogByStudentId(CourseResourceEntity entity, Long studentId) {

        // 获取主学生信息
        ClassStudentResultDTO mainStudent = R.as(classStudentClient.findVirtualClassStudentByClassIdAndUserId(entity.getClassId(), studentId));

        LambdaQueryWrapper<CourseResourceStudentLogEntity> logWrapper = new LambdaQueryWrapper();
        logWrapper.eq(CourseResourceStudentLogEntity::getContentId, entity.getId());
        logWrapper.eq(CourseResourceStudentLogEntity::getStudentId, mainStudent.getStudentId());
        CourseResourceStudentLogEntity logEntity = resourceStudentLogManager.getOne(logWrapper);
        if (Objects.isNull(logEntity)) {
            CourseResourceStudentLogEntity newLogEntity = new CourseResourceStudentLogEntity();
            logEntity.setClassId(entity.getClassId());
            logEntity.setStudentId(mainStudent.getStudentId());
            logEntity.setContentId(entity.getId());
            logEntity.setContentType(entity.getContentType());
            logEntity.setStudyStatus(CourseResourseStudyStatusEnum.UNSTUDIED.getCode());
            resourceStudentLogManager.save(newLogEntity);
        }
    }

    /**
     * 批量添加学生日记记录信息
     * @author dzy
     */
    @Override
    public void syncStudentLog(CourseResourceEntity entity) {

        // 获取学生历史学习记录日志
        List<ClassStudentResultDTO> students = R.as(classStudentClient.findClassMasterStudentByClassId(entity.getClassId()));
        List<CourseResourceStudentLogEntity> oldEntities = resourceStudentLogManager.listByContentId(entity.getId());
        // 同步学生资料学习日志
        if (CollectionUtils.isNotEmpty(students)) {
            ArrayList<CourseResourceStudentLogEntity> logEntities = new ArrayList<>();
            // 校验去除历史数据
            if (CollectionUtils.isNotEmpty(oldEntities)) {
                List<Long> oldStuIds = oldEntities.stream().map(CourseResourceStudentLogEntity::getStudentId).collect(Collectors.toList());
                students = students.stream().filter(v -> !oldStuIds.contains(v.getStudentId())).collect(Collectors.toList());
            }
            for (ClassStudentResultDTO student : students) {
                CourseResourceStudentLogEntity logEntity = new CourseResourceStudentLogEntity();
                logEntity.setClassId(entity.getClassId());
                logEntity.setStudentId(student.getStudentId());
                logEntity.setContentId(entity.getId());
                logEntity.setContentType(entity.getContentType());
                logEntity.setStudyStatus(CourseResourseStudyStatusEnum.UNSTUDIED.getCode());
                logEntities.add(logEntity);
            }
            resourceStudentLogManager.saveBatch(logEntities);
        }
    }

    /**
     * 批量多班级添加学生日记记录信息
     * @author dzy
     */
    @Override
    public void syncBatchStudentLog(List<CourseResourceEntity> list) {
        // 定义批量添加List
        ArrayList<CourseResourceStudentLogEntity> logEntities = new ArrayList<>();
        list.forEach(entity -> {
            // 获取学生历史学习记录日志
            List<ClassStudentResultDTO> students = R.as(classStudentClient.findClassMasterStudentByClassId(entity.getClassId()));
            List<CourseResourceStudentLogEntity> oldEntities = resourceStudentLogManager.listByContentId(entity.getId());
            // 同步学生课件学习日志
            if (CollectionUtils.isNotEmpty(students)) {
                // 校验去除历史数据
                if (Objects.isNull(oldEntities) && oldEntities.size() > 0) {
                    List<Long> oldStuIds = oldEntities.stream().map(CourseResourceStudentLogEntity::getStudentId).collect(Collectors.toList());
                    students = students.stream().filter(v -> !oldStuIds.contains(v.getStudentId())).collect(Collectors.toList());
                }
                for (ClassStudentResultDTO student : students) {
                    CourseResourceStudentLogEntity logEntity = new CourseResourceStudentLogEntity();
                    logEntity.setClassId(entity.getClassId());
                    logEntity.setStudentId(student.getStudentId());
                    logEntity.setContentId(entity.getId());
                    logEntity.setContentType(entity.getContentType());
                    logEntity.setStudyStatus(CourseResourseStudyStatusEnum.UNSTUDIED.getCode());
                    logEntities.add(logEntity);
                }
            }
        });
        resourceStudentLogManager.saveBatch(logEntities);
    }

    /**
     * 更新学总得分
     * @author dzy
     */
    @Override
    public void refreshStudentLog(Long contentId, Long studentId, boolean flag) {

        // 获取学生日志记录数据
        LambdaQueryWrapper<CourseResourceStudentLogEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseResourceStudentLogEntity::getContentId, contentId);
        wrapper.eq(CourseResourceStudentLogEntity::getStudentId, studentId);
        CourseResourceStudentLogEntity logEntity = resourceStudentLogManager.getOne(wrapper);

        // 获取答题记录
        LambdaQueryWrapper<CourseResourceInteractionLogEntity> interactionWrapper = new LambdaQueryWrapper<>();
        interactionWrapper.eq(CourseResourceInteractionLogEntity::getContentId, contentId);
        interactionWrapper.eq(CourseResourceInteractionLogEntity::getStudentId, studentId);
        List<CourseResourceInteractionLogEntity> interactionLogList = resourceInteractionLogManager.list(interactionWrapper);

        if (CollectionUtils.isNotEmpty(interactionLogList)) {
            BigDecimal studentScore = new BigDecimal(0);
            for (CourseResourceInteractionLogEntity interactionLog : interactionLogList) {
                studentScore = studentScore.add(interactionLog.getScore());
            }
            if (Objects.nonNull(logEntity)) {
                logEntity.setStudentScore(studentScore);
                // 互动视频修改提交时间
                if (flag) { logEntity.setLastAccessTime(LocalDateTime.now()); }
                resourceStudentLogManager.updateById(logEntity);
            }

        }
    }

}
